#include "lineview.h"
#include <QFile>
#include <QHBoxLayout>
#include <QApplication>
#include <QLabel>
#include <QMovie>
#include <QEvent>
#include <QBitmap>
#include "common.h"
#include "huaqimovie.h"

extern int interval_unequal_offset;
extern int all_unequal_offset;

int LineView::m_id = qRegisterMetaType<LineView*>();

LineView::LineView(QWidget *parent)
    :ViewObject(parent)
    ,m_paramLineView(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_DeleteOnClose);

#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
        m_objectParam = new ParamObject;

    if (m_paramLineView == NULL)
        m_paramLineView = new LineViewParam;
}

LineView::~LineView()
{
    if (m_paramLineView != NULL)
        delete m_paramLineView;

    if (m_objectParam != NULL)
        delete  m_objectParam;

    m_objectParam = NULL;
    m_paramLineView = NULL;
}

void LineView::SetOffset(int offset)
{
    if (offset == 0) return;
    int stid = m_objectParam->GetStId();
    int curr_id = mProtocolData->curr_or_next_id;
    int start_id = mProtocolData->start_id;
    int stop_id = mProtocolData->stop_id;
    int rundir = RUN_INVALID;
    if (start_id < stop_id)
        rundir = RUN_UP;
    else if (start_id > stop_id)
        rundir = RUN_DOWN;

    /*设置不等间距的偏移量*/
    bool is_mirror = mProtocolData->file_path.contains("mirror");

    //当前站都是偏移一个偏移量
    if (curr_id == stid)
    {
        if (is_mirror)
            mOffsetX = 2*offset;
        else
            mOffsetX = 0;
    }

    //当前站后面的站都是偏移两个偏移量
    //上行或者下行镜像一组(大号在右侧)，下行或者上行镜像一组(小号在右侧)
    if ((is_mirror && rundir == RUN_DOWN) || (!is_mirror && rundir == RUN_UP))
    {
        if (stid > curr_id)
            mOffsetX = 2*offset;
    }
    else
    {
        if (stid < curr_id)
            mOffsetX = 2*offset;
    }
    /**************************************************/
}

void LineView::ShowObject()
{ 
    if (!m_paramLineView || !m_objectParam) return;

    int stid = m_objectParam->GetStId();
    LoadStationPic(stid, mFilename);
    url = m_paramLineView->m_resNormalPath;

    int interval_config_offset = interval_unequal_offset;
    int all_config_offset = all_unequal_offset;

    if (mProtocolData)
    {
        int curr_id = mProtocolData->curr_or_next_id;
        int start_id = mProtocolData->start_id;
        int stop_id = mProtocolData->stop_id;
        int rundir = RUN_INVALID;
        if (start_id < stop_id)
            rundir = RUN_UP;
        else if (start_id > stop_id)
            rundir = RUN_DOWN;

        if (mFilename.contains(IntervalFlag))
            SetOffset(interval_config_offset);
        if (mFilename.contains(AllFlag))
            SetOffset(all_config_offset);

        if (curr_id == INVALID_NUM || stid == 0 || curr_id == 0)
        {
            url = m_paramLineView->m_resNormalPath;
        }
        else
        {
            if (curr_id == stid)
            {
                url = m_paramLineView->m_resCurrentPath;
            }
            else if (stid > curr_id)
            {
                if (rundir == RUN_UP)
                {
                    url =  m_paramLineView->m_resFuturePath;
                }
                else if (rundir == RUN_DOWN)
                {
                    url =  m_paramLineView->m_resPassPath;
                }
            }
            else if (stid < curr_id)
            {
                if (rundir == RUN_UP)
                {
                    url = m_paramLineView->m_resPassPath;
                }
                else if (rundir == RUN_DOWN)
                {
                    url =  m_paramLineView->m_resFuturePath;
                }
            }
            else
            {
                url = m_paramLineView->m_resNormalPath;
            }
        }

        foreach (int id, mProtocolData->skip_list)
        {
            if (id == stid)
            {
                url = m_paramLineView->m_resSkipPath;
                break;
            }
        }

        if (rundir == RUN_UP)
        {
            if (url.contains("all_line") && stid == start_id)
            {
                url = m_paramLineView->m_resCrossPath;
            }
            if (stid < start_id || stid > stop_id)
            {
                url = m_paramLineView->m_resCrossPath;
            }
        }
        else if (rundir == RUN_DOWN)
        {
            if (url.contains("all_line") && stid == start_id)
            {
                url = m_paramLineView->m_resCrossPath;
            }
            if (stid > start_id || stid < stop_id)
            {
                url = m_paramLineView->m_resCrossPath;
            }
        }
    }
    else
    {
        url = m_paramLineView->m_resNormalPath;
    }

    ShowUrl();
}

void LineView::LoadStationPic(int stid, QString filename)
{
    if (filename == "")
        return;

    QString file_name = filename.left(filename.size() - 4);
    QStringList list = file_name.split("_");
    QString flag = list.at(ParamType);

    /*
     * LineView控件是否加载镜像图片需要同时考虑文件名中是否含有mirror以及该控件的showleft属性是否为true
     */
    bool isShowMirror = false;
    if (filename.contains("mirror")) {
        if (m_objectParam->GetShowLeft()) {
            isShowMirror = false;
        } else {
            isShowMirror = true;
        }
    } else {
        if (m_objectParam->GetShowLeft()) {
            isShowMirror = true;
        } else {
            isShowMirror = false;
        }
    }

    if (isShowMirror)//镜像
    {
        m_paramLineView->m_resNormalPath = QString("%1_line_future_mirror_%2").arg(flag).arg(stid);
        m_paramLineView->m_resSkipPath = QString("%1_line_skip_mirror_%2").arg(flag).arg(stid);
        m_paramLineView->m_resCrossPath = QString("%1_line_cross_mirror_%2").arg(flag).arg(stid);
        m_paramLineView->m_resFuturePath = QString("%1_line_future_mirror_%2").arg(flag).arg(stid);
        m_paramLineView->m_resPassPath = QString("%1_line_pass_mirror_%2").arg(flag).arg(stid);
        m_paramLineView->m_resCurrentPath = QString("%1_line_current_mirror_%2").arg(flag).arg(stid);
    }
    else
    {
        m_paramLineView->m_resNormalPath = QString("%1_line_future_%2").arg(flag).arg(stid);
        m_paramLineView->m_resSkipPath = QString("%1_line_skip_%2").arg(flag).arg(stid);
        m_paramLineView->m_resCrossPath = QString("%1_line_cross_%2").arg(flag).arg(stid);
        m_paramLineView->m_resFuturePath = QString("%1_line_future_%2").arg(flag).arg(stid);
        m_paramLineView->m_resPassPath = QString("%1_line_pass_%2").arg(flag).arg(stid);
        m_paramLineView->m_resCurrentPath = QString("%1_line_current_%2").arg(flag).arg(stid);
    }
}
void LineView::GetAttribute(std::string &attribute)
{   
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();

    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void LineView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
    {
         LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);
    }

    if (CheckJsonValueType(root, "zindex", Json::stringValue))
    {
         m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());
    }

    if (CheckJsonValueType(root, "stid", Json::stringValue))
    {
        m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());
    }
    if (CheckJsonValueType(root, "x", Json::stringValue))
    {
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());
    }
    if (CheckJsonValueType(root, "y", Json::stringValue))
    {
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());
    }
    if (CheckJsonValueType(root, "w", Json::stringValue))
    {
        m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());
    }
    if (CheckJsonValueType(root, "h", Json::stringValue))
    {
        m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());
    }

    if (CheckJsonValueType(root, "name", Json::stringValue))
    {
        m_objectParam->SetName(QString::fromStdString(root["name"].asString()));
    }
}

void LineView::ParseXML(QDomElement* xmlDomEle)
{
    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name",""));
    QVariant var = QVariant::fromValue(xmlDomEle->attribute("showleft", "false"));
    m_objectParam->SetShowLeft(var.toBool());
}

void LineView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type", m_objectParam->GetObjectName());
    dom->setAttribute("zindex",QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid",QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x",QString::number(m_objectParam->GetX()));
    dom->setAttribute("y",QString::number(m_objectParam->GetY()));
    dom->setAttribute("w",QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h",QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name",m_objectParam->GetName());
    QVariant var = QVariant::fromValue(m_objectParam->GetShowLeft());
    dom->setAttribute("showleft", var.toString());
}


